<template>
  <div>
    <el-card shadow="never">
      <header-title title="电表管理"></header-title>
    </el-card>
    <el-card shadow="never">
      <el-row>
        <el-col :span="21">
          <div>
            电表编号:
            <el-input
              v-model="searchName"
              placeholder="请输入内容"
              size="small"
              style="margin-right: 15px;width: 150px;"
            ></el-input>
            <el-button
              @click="search"
              class="button"
              size="small"
              round
              icon="el-icon-search"
              style="margin: 10px 0;"
            >查询</el-button>
          </div>
        </el-col>
        <el-col :span="3">
          <el-button @click="add" class="button" size="small" round>添加电表</el-button>
        </el-col>
      </el-row>
    </el-card>
    <el-card shadow="never">
      <div>
        <el-table
          :data="tableData"
          v-loading="loading"
          @selection-change="handleSelectionChange"
          style="width: 100%"
        >
          <el-table-column type="selection" width="55" label="全选开户"></el-table-column>
          <el-table-column prop="collectorNo" label="采集器编号"></el-table-column>
          <el-table-column prop="wattHourMeterNo" label="电表表号"></el-table-column>
          <el-table-column prop="wattHourMeterModel" label="型号"></el-table-column>
          <el-table-column prop="isOnline" label="是否在线"></el-table-column>
          <el-table-column prop="businessName" label="商户名称"></el-table-column>
          <el-table-column prop="stallName" label="摊位名称"></el-table-column>
          <el-table-column prop="sidName" label="设备供应商名称"></el-table-column>
          <el-table-column prop="isOpenAccount" label="是否开户"></el-table-column>
          <el-table-column prop="price" label="单价(每吨)"></el-table-column>
          <el-table-column prop="purchaseCount" label="充值次数"></el-table-column>
          <el-table-column prop="waterValveState" label="电阀状态"></el-table-column>
          <el-table-column prop="isCancelAccount" label="是否销户"></el-table-column>
          <el-table-column label="操作" width="290" fixed="right">
            <template slot-scope="scope">
              <el-button @click="readingMeter(scope.row)" type="text" style="color:#3dc2c2;">抄表</el-button>
              <el-button @click="onMeter(scope.row)" type="text" style="color:#71dc80;">开阀</el-button>
              <el-button @click="offMeter(scope.row)" type="text" style="color:#55b7ff;">关阀</el-button>
              <el-button @click="reset(scope.row)" type="text" style="color:#3dc2c2;">清零</el-button>
              <el-button @click="openAnAccount(scope.row)" type="text" style="color:#71dc80;">开户</el-button>
              <el-button @click="remove(scope.row)" type="text" style="color:#dc1033;">删除</el-button>
            </template>
          </el-table-column>
          <div slot="empty">
            <img src="../../../assets/blank_tip_page/blank_tip_page.png" alt />
          </div>
        </el-table>
        <el-pagination
          :page-size="perPage"
          :current-page="page"
          :total="total"
          @current-change="changePage"
          style="margin-top: 15px;"
          background
          layout="prev, pager, next"
        ></el-pagination>
      </div>
    </el-card>
    <el-dialog title="添加电表" :visible.sync="addDialog" @close="close" v-if="addDialog">
      <div>
        <el-form :model="addModel" label-width="120px" ref="addModel" :rules="rules">
          <el-form-item label="供应商名称：" prop="sidName">
            <el-select v-model="addModel.sidName" @change="changeSidName" placeholder="请选择">
              <el-option
                v-for="item in supplierList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="电表编号：" prop="wattHourMeterNo">
            <el-input v-model="addModel.wattHourMeterNo" style="width:194px"></el-input>
          </el-form-item>
          <!--<el-form-item label="电表型号：" prop="wattHourMeterModel">
            <el-input v-model="addModel.wattHourMeterModel"></el-input>
          </el-form-item>-->
          <el-form-item label="摊位名称：" prop="marketId">
            <my-select
              ref="mySelectStallName"
              url="api/v1/backend/public/contract/stall"
              :queryParamers="{marketId: this.marketId, type: 1}"
              @selected="mySelectedStall"
            ></my-select>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="save('addModel')">保存电表</el-button>
      </div>
    </el-dialog>

    <el-dialog title="电表开户" :visible.sync="openDialog" @close="close">
      <div>
        <el-form :model="openModel" label-width="130px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="金额" prop="money">
                <el-input v-model="openModel.params.money">
                  <template slot="append">元</template>
                </el-input>
              </el-form-item>
              <el-form-item label="电价" prop="price">
                <el-input v-model="openModel.params.price">
                  <template slot="append">元</template>
                </el-input>
              </el-form-item>
              <el-form-item label="囤积限量" prop="hoard">
                <el-input v-model="openModel.params.hoard">
                  <template slot="append">元</template>
                </el-input>
              </el-form-item>
              <el-form-item label="透支金额" prop="overdraw">
                <el-input v-model="openModel.params.overdraw">
                  <template slot="append">元</template>
                </el-input>
              </el-form-item>
              <el-form-item label="显示报警金额" prop="display_warning">
                <el-input v-model="openModel.params.display_warning">
                  <template slot="append">元</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="断电报警金额" prop="pulloff_warning">
                <el-input v-model="openModel.params.pulloff_warning">
                  <template slot="append">元</template>
                </el-input>
              </el-form-item>
              <el-form-item label="负荷限制功率" prop="load_limit">
                <el-input v-model="openModel.params.load_limit">
                  <template slot="append">kw</template>
                </el-input>
              </el-form-item>
              <el-form-item label="超过负荷断电后" prop="load_delay">
                <el-input v-model="openModel.params.load_delay">
                  <template slot="append">分钟</template>
                </el-input>
              </el-form-item>
              <el-form-item label="屏幕轮显时间" prop="display_time">
                <el-input v-model="openModel.params.display_time">
                  <template slot="append">分钟</template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="setOpen">设置开户</el-button>
      </div>
    </el-dialog>
    <el-dialog title="验证密码" :visible.sync="dialogpass" v-if="dialogpass" width="25%">
      <el-form :model="passdata" :rules="rulespass" ref="pwd">
        <el-form-item label="请输入密码" label-width="100px" prop="password1">
          <el-input v-model="passdata.password1" autocomplete="off" show-password></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogpass = false" size="mini">取 消</el-button>
        <el-button type="primary" @click="submitpass('pwd')" size="mini">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import HeaderTitle from "@/components/HeaderTitle";
import MySelect from "@/components/MySelect";
import store from "@/store";
export default {
  name: "electricMeter",
  components: {
    HeaderTitle,
    MySelect
  },
  data() {
    return {
      marketId: 0,
      loading: true,
      tableData: [],
      searchName: "", // false	true	采集器号或水号表编号
      perPage: 10, // 每页显示10条
      page: 1, // 当前页
      total: 0,

      addDialog: false,
      addModel: {
        wattHourMeterNo: "", //	string	true	电表编号
        wattHourMeterModel: "", //	string	false	电表型号
        stallId: 0, //	int	true	摊位id
        stallName: "", //	string	true	摊位名称
        sidName: "" //	string	true	供应商名称
      },
      //密码框
      dialogpass: false,
      passdata: {
        password1: ""
      },
      resetId: "",
      openAnId: "",
      btn: "",
      // 供应商列表
      supplierList: [],

      // 开户 弹框 变量
      openDialog: false,
      // openStallId: 0,
      openModel: {
        id: 0, // int	true	水表id
        params: {
          // json	true	开户参数
          money: "0", //	int	true	金额	单位：分
          price: "1", //	int	true	电价	单位：分，范围：1-9999
          hoard: "99999.9", //	int	true	囤积限量	单位：分，电表允许的最大剩余金额，如果充值后剩余金额超过此值拒绝充值,0-19999999，默认：99999.9
          overdraw: "0", //	int	true	透支金额	单位：分，选填 透支金额 （电表允许的欠费金额） 范围：0-99999900 默认：0，不允许欠费
          display_warning: "100", //	int	true	显示报警金额	单位：分，剩余金额低于此值报警灯闪烁） 范围 0-99999900,默认 100 元
          pulloff_warning: "0", //	int	true	断电报警金额	单位：分，剩余金额低于此值断电报警，需用合闸命令）范围 0-99999900 ，默认 0 元
          load_limit: "10", //	int	true	负荷限制功率	单位：分，0-999999kw （负荷超过此值断电，过一段时间再通电） 默认 10kw
          load_delay: "5", //	int	true	超过负荷断电后	延迟上电时间 0-99 分钟 ，默认 5 分钟
          display_time: "5" //	int	true	屏幕轮显时间	0-99秒 默认5秒
        },
        optType: 1 // int	true	开户类型	1.设置单条 2.全部开户，即1时，id生效,否则全部开户
      },
      flag: 1, // 1单表开户，2全部开户
      multipleSelection: [],
      rules: {
        sidName: [
          { required: true, message: "请选择供应商名称", trigger: "change" }
        ],
        wattHourMeterNo: [
          { required: true, message: "请输入电表编号", trigger: "change" }
        ],
        marketId: [
          { required: true, message: "请选择摊位名称", trigger: "change" }
        ]
      },
      rulespass: {
        password1: [
          { required: true, message: "请选择密码", trigger: "change" },
          {
            pattern: /^[a-zA-Z\d\(\)（）\-\_]+$/,
            message: "密码只可以包含数字，字母，-，_，()",
            trigger: "change"
          }
        ]
      }
    };
  },
  watch: {
    "$store.state.app.marketId"(val, oldVal) {
      this.getDataList(this.searchName, this.perPage, this.page);
    }
  },
  mounted() {
    this.marketId = store.state.app.marketId;
    this.getDataList(this.searchName, this.perPage, this.page);
  },
  methods: {
    // 获取数据列表
    getDataList(searchName) {
      this.$store
        .dispatch("waterElectricMeter/fetchElectricMeterList", { searchName })
        .then(data => {
          this.loading = false;
          for (let i = 0; i < data.items.length; i++) {
            if (data.items[i].isOnline === 1) {
              data.items[i].isOnline = "在线";
            } else {
              data.items[i].isOnline = "离线";
            }
            if (data.items[i].isOpenAccount === 1) {
              data.items[i].isOpenAccount = "已开户";
            } else {
              data.items[i].isOpenAccount = "未开户";
            }
            if (data.items[i].waterValveState === 1) {
              data.items[i].waterValveState = "开启";
            } else {
              data.items[i].waterValveState = "关闭";
            }
            if (data.items[i].isCancelAccount === 1) {
              data.items[i].isCancelAccount = "已销户";
            } else {
              data.items[i].isCancelAccount = "正常";
            }
          }
          this.tableData = data.items;
          this.total = data.total;
        })
        .catch(err => {
          this.loading = false;
          this.tableData = [];
          this.total = 0;
        });
    },
    search() {
      this.page = 1;
      this.getDataList(this.searchName, this.perPage, this.page);
    },
    changePage(num) {
      this.page = num;
      this.getDataList(this.searchName, this.perPage, num);
    },
    // 点击添加
    add() {
      this.addDialog = true;
      // 获取供应商列表
      this.$store
        .dispatch("waterElectricMeter/fetchSupplierList")
        .then(data => {
          let items = [];
          for (let item of data) {
            items.push({
              value: item.sid + "",
              label: item.name
            });
          }
          this.supplierList = items;
        })
        .catch(err => {
          this.supplierList = [];
        });
    },
    changeSidName(type) {
      this.addModel.sid = type;
      // 用原数据查id对应name
      let obj = {};
      obj = this.supplierList.find(item => {
        // 这里的 this.supplierList 就是上面遍历的数据源
        return item.value === type; // 筛选出匹配数据 数据源里的 id 等于 当前选中的 id
      });
      this.addModel.sidName = obj.label;
    },
    // 摊位 自动完成
    mySelectedStall(obj) {
      this.addModel.stallId = obj.exData.id;
      this.addModel.stallName = obj.exData.name;
    },
    save(addModal) {
      console.log(this.addModel);
      this.$refs[addModal].validate(valid => {
        if (valid) {
          this.$store
            .dispatch(
              "waterElectricMeter/fetchSaveElectricMeter",
              this.addModel
            )
            .then(data => {
              console.log("success?");
              console.log(data);
              // 成功之后调用列表
              if (data) {
                this.$message({
                  type: "success",
                  message: "新增成功!"
                });
              }
              this.getDataList(this.searchName, this.perPage, this.page);
              // 调用 close
              this.addModel = {};
              this.$refs["mySelectStallName"].clear();
            })
            .catch(err => {});
        } else {
          this.$message.error("有必填项未填");
          return false;
        }
      });
    },
    close() {
      this.addModel = {};
    },
    // 点击删除
    remove(row) {
      let id = row.id;
      //        this.$confirm(`是否确定要删除采集器 "${row.sid}"`, '提示', {
      this.$confirm(`是否确定要删除?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$store
            .dispatch("waterElectricMeter/fetchRemoveElectricMeter", { id })
            .then(data => {
              console.log(data.data);
              if (data.data) {
                this.$message({
                  type: "success",
                  message: "删除成功!"
                });
              }
              this.getDataList(this.searchName, this.perPage, this.page);
            });
        })
        .catch(err => {});
    },
    // 清零
    reset(row) {
      (this.resetId = row.id), (this.btn = "reset"), (this.dialogpass = true);
    },
    resetfn() {
      this.$confirm(`要清零?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$store
            .dispatch("waterElectricMeter/fetchResetElectric", {
              id: this.resetdata.id
            })
            .then(data => {
              console.log(data.data);
              if (data.data) {
                this.$message({
                  type: "success",
                  message: "清零成功!"
                });
              }
              this.getDataList(this.searchName, this.perPage, this.page);
            });
        })
        .catch(err => {});
    },
    submitpass(pwd) {
      this.$refs[pwd].validate(valid => {
        if (valid) {
          this.$store
            .dispatch("yzpassword/getPassword", {
              password: this.passdata.password1
            })
            .then(data => {
              console.log(data);
              if (data.state == true) {
                this.dialogpass = false;
                if (this.btn == "reset") {
                  this.resetfn();
                }
                if (this.btn == "open") {
                  this.openAnfn();
                }
              } else {
                this.$message.error("密码错误");
              }
            });
        } else {
          this.dialogpass = true;
          this.$message.error("有必填项未填");
          return false;
        }
      });
    },
    // 全选 开户
    handleSelectionChange(val) {
      console.log("全选 开户");
      console.log(val);
      this.multipleSelection = val;
      if (val.length !== 0) {
        this.openDialog = true;
        this.flag = 2;
        this.openModel = {
          id: 0, // int	true	水表id
          params: {
            // json	true	开户参数
            money: "0", //	int	true	金额	单位：分
            price: "1", //	int	true	电价	单位：分，范围：1-9999
            hoard: "99999.9", //	int	true	囤积限量	单位：分，电表允许的最大剩余金额，如果充值后剩余金额超过此值拒绝充值,0-19999999，默认：99999.9
            overdraw: "0", //	int	true	透支金额	单位：分，选填 透支金额 （电表允许的欠费金额） 范围：0-99999900 默认：0，不允许欠费
            display_warning: "100", //	int	true	显示报警金额	单位：分，剩余金额低于此值报警灯闪烁） 范围 0-99999900,默认 100 元
            pulloff_warning: "0", //	int	true	断电报警金额	单位：分，剩余金额低于此值断电报警，需用合闸命令）范围 0-99999900 ，默认 0 元
            load_limit: "10", //	int	true	负荷限制功率	单位：分，0-999999kw （负荷超过此值断电，过一段时间再通电） 默认 10kw
            load_delay: "5", //	int	true	超过负荷断电后	延迟上电时间 0-99 分钟 ，默认 5 分钟
            display_time: "5" //	int	true	屏幕轮显时间	0-99秒 默认5秒
          },
          optType: 2 // int	true	开户类型	1.设置单条 2.全部开户，即1时，id生效,否则全部开户
        };
      }
    },
    // 点击 开户
    openAnAccount(row) {
      (this.openAnId = row.stallId),
        (this.btn = "open"),
        (this.dialogpass = true);
    },

    openAnfn() {
      this.openDialog = true;
      this.flag = 1;
      // 获取 合同 价格
      this.$store
        .dispatch("waterElectricMeter/fetchContectPrice", {
          openStallId: this.openAnId
        })
        .then(data => {
          this.openModel = {
            id: 0, // int	true	水表id
            params: {
              // json	true	开户参数
              money: "0", //	int	true	金额	单位：分
              price: "1", //	int	true	电价	单位：分，范围：1-9999
              hoard: "99999.9", //	int	true	囤积限量	单位：分，电表允许的最大剩余金额，如果充值后剩余金额超过此值拒绝充值,0-19999999，默认：99999.9
              overdraw: "0", //	int	true	透支金额	单位：分，选填 透支金额 （电表允许的欠费金额） 范围：0-99999900 默认：0，不允许欠费
              display_warning: "100", //	int	true	显示报警金额	单位：分，剩余金额低于此值报警灯闪烁） 范围 0-99999900,默认 100 元
              pulloff_warning: "0", //	int	true	断电报警金额	单位：分，剩余金额低于此值断电报警，需用合闸命令）范围 0-99999900 ，默认 0 元
              load_limit: "10", //	int	true	负荷限制功率	单位：分，0-999999kw （负荷超过此值断电，过一段时间再通电） 默认 10kw
              load_delay: "5", //	int	true	超过负荷断电后	延迟上电时间 0-99 分钟 ，默认 5 分钟
              display_time: "5" //	int	true	屏幕轮显时间	0-99秒 默认5秒
            },
            optType: 1 // int	true	开户类型	1.设置单条 2.全部开户，即1时，id生效,否则全部开户
          };
          this.openModel.id = row.id;
          this.openModel.optType = 1;
          if (
            data.isExistsContract === true &&
            data.isExistsElecPrice === true
          ) {
            this.openModel.params.price = data.elecPrice / 100;
          } else {
            this.openModel.params.price = 1;
          }
        })
        .catch(err => {});
    },

    // 保存 开户
    setOpen() {
      this.openDialog = false;
      this.openModel.params.money = this.openModel.params.money * 100;
      this.openModel.params.price = this.openModel.params.price * 100;
      this.openModel.params.hoard = this.openModel.params.hoard * 100;
      this.openModel.params.overdraw = this.openModel.params.overdraw * 100;
      this.openModel.params.display_warning =
        this.openModel.params.display_warning * 100;
      this.openModel.params.pulloff_warning =
        this.openModel.params.pulloff_warning * 100;
      this.openModel.params = JSON.stringify(this.openModel.params);
      console.log(JSON.stringify(this.openModel.params));
      console.log(this.openModel);
      this.$store
        .dispatch("waterElectricMeter/fetchElectricOpenAcount", this.openModel)
        .then(data => {
          console.log(data);
          if (data) {
            this.$message({
              type: "success",
              message: "开户设置成功!"
            });
            this.getDataList(this.searchName, this.perPage, this.page);
          }
        })
        .catch(err => {});
    },
    // 抄表
    readingMeter(row) {
      let id = row.id;
      this.$confirm(`点击了抄表数据?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$store
            .dispatch("waterElectricMeter/fetchReadElectricMeter", { id })
            .then(data => {
              console.log(data.data);
              if (data.data) {
                this.$message({
                  type: "success",
                  message: "抄表成功!"
                });
              }
              this.getDataList(this.searchName, this.perPage, this.page);
            });
        })
        .catch(err => {});
    },
    // 开阀
    onMeter(row) {
      // controlStatus	int	true	闸门状态 1.合闸 2.拉闸
      console.log(row);
      let id = row.id;
      const controlStatus = 1;
      this.$confirm(`设置开阀?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$store
            .dispatch("waterElectricMeter/fetchPullElectricMeter", {
              id,
              controlStatus
            })
            .then(data => {
              console.log(data.data);
              if (data.data) {
                this.$message({
                  type: "success",
                  message: "设置成功!"
                });
              }
              this.getDataList(this.searchName, this.perPage, this.page);
            });
        })
        .catch(err => {});
    },
    // 关阀
    offMeter(row) {
      //        controlStatus	int	true	闸门状态 1.合闸 2.拉闸
      console.log(row);
      let id = row.id;
      const controlStatus = 2;
      this.$confirm(`设置关阀?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$store
            .dispatch("waterElectricMeter/fetchPullElectricMeter", {
              id,
              controlStatus
            })
            .then(data => {
              console.log(data.data);
              if (data.data) {
                this.$message({
                  type: "success",
                  message: "设置成功!"
                });
              }
              this.getDataList(this.searchName, this.perPage, this.page);
            });
        })
        .catch(err => {});
    }
  }
};
</script>

<style lang="scss" scoped>
.button {
  background: #64d9d6;
  color: #fff;
  margin-left: 40px;
}
</style>
